import {Component, OnInit} from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators
} from '@angular/forms';
import {NzMessageService, NzDropdownContextComponent, NzDropdownService, NzMenuItemDirective} from 'ng-zorro-antd';

import {Knowledge} from './model/knowledge';
import {PageInfo} from '@core/model/pageInfo';

import {I18NService} from '@core/i18n/i18n.service';
import {PopupService} from '@shared/popup/popup.service';
import {KnowledgeService} from './services/knowledge.service';

import {KnowledgeModifyComponent} from './modify/knowledge-modify.component';

@Component({
  templateUrl: './knowledge-list.html'
})
export class KnowledgeListComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private i18nService: I18NService,
    private knowledgeService: KnowledgeService,
    private fb: FormBuilder,
    private popupService: PopupService
  ) {
    this.validateForm = this.fb.group({
      knowledgeName: ''
    });
  }
  knowledgeName='';
  data: Knowledge[] = [];
  knowledgeList: Knowledge[] = [];
  page = {
    pageNo: 1,
    pageSize: 10,
    total: 1
  };

  _loading = false;
  arr = [];
  expandDataCache = {};

  tempEditObject = {};

  validateForm: FormGroup;
  index: number;

  ngOnInit(): void {
    this.getKnowledgeByPage(true);
  }

  collapse(array, data, $event: boolean): void {
    if ($event === false) {
      if (data.knowledgeList) {
        data.knowledgeList.forEach(d => {
          const target = array.find(a => a.id === d.id);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    } else {
      if (data.dept === 3 && !data.knowledgeList) {
        this.knowledgeService.getKnowledgeListByPid(data.id)
          .subscribe(res => {
            data.knowledgeList = res;
            data.expand = true;
            for (let i = 0; i < data.knowledgeList.length; i++) {
              data.knowledgeList[i].expand = false;
              data.knowledgeList[i].level = data.level + 1;
              data.knowledgeList[i].parent = data;
            }
            for (let i = 0; i < array.length; i++) {
              if (array[i].id === data.id) {
                this.index = i;
              }
            }
            for (let i = 1; i <= data.knowledgeList.length - 1; i++) {
              array.splice(this.index + i, 0, data.knowledgeList[i]);
            }
          });
      }
    }
  }

  convertTreeToList(root) {
    const stack = [], array = [], hashMap = {};
    stack.push({...root, level: 0, expand: false});
    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      const null_data = [];
      if (node.knowledgeList) {
        for (let i = node.knowledgeList.length - 1; i >= 0; i--) {
          stack.push({...node.knowledgeList[i], level: node.level + 1, expand: false, parent: node});
        }
      }
    }
    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }

  getKnowledgeByPage(reset = false): void {
    if (reset) {
      this.page.pageNo = 1;
    }
    if (!this._loading) {
      this._loading = true;
      this.knowledgeService.getKnowledgeByPage(this.page.pageNo, this.page.pageSize, this.knowledgeName)
        .subscribe(res => {
          this._loading = false;
          this.data = res.records;
          this.page.total = res.total;
          res.records.forEach(item => {
            this.expandDataCache[item.id] = this.convertTreeToList(item);
            this.tempEditObject[item.id] = {};
          });
        }, err => {
          this._loading = false;
        });
    }
  }

  showModify(item?: any): void {
    let params = {};
    let title = '添加菜单';
    if (item !== undefined) {
      params = {
        id: item.id
      };
      title = item.knowledgeName + '菜单修改';
    }
    this.popupService.create({
      title: title,
      content: KnowledgeModifyComponent,
      componentParams: params,
      width: 620,
      onSubmit: (res) => {
        this.getKnowledgeByPage(true);
      },
      onCancel: (res) => {
        console.log(res);
      }
    }).afterClose.subscribe(res => {
      console.log(res);
    });
  }

  delete(id: number): void {
    if (!this._loading) {
      this._loading = true;
      this.knowledgeService.deltetKnowledge(id)
        .subscribe(res => {
          if (res) {
            this.message.success(this.i18nService.translate('modify.return.delete_success'));
            this._loading = false;
            this.getKnowledgeByPage();
          } else {
            this.message.error(this.i18nService.translate('modify.return.delete_error'));
            this._loading = false;
          }
        }, err => {
          this._loading = false;
        });
    }
  }

  search(): void {
    this.getKnowledgeByPage(true);
  }

  refresh(): void {
    this.knowledgeName='';
    this.getKnowledgeByPage(true);
  }
}
